package com.devshephard.example;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

public class NSyncProducer {

    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        producer.setNamesrvAddr("192.168.81.130:9876");
        // 指定异步发送失败后不进行重试发送
        producer.setRetryTimesWhenSendAsyncFailed(0);
        // 指定新创建的Topic的Queue数量为2，默认为4
        producer.setDefaultTopicQueueNums(2);
        producer.start();
        //生产10条消息
        for (int i = 1; i < 2; i++) {
            //指定消息内容，并将内容转换成二进制数组
            byte[] body = ("这是一个批量测试----first").getBytes();
            try {
                Message msg = new Message("someTopic", "myTag", body);
                // 异步发送。指定结果回调内容
                producer.send(msg, new SendCallback() {

                    public void onSuccess(SendResult sendResult) {
                        System.out.println(sendResult);
                    }

                    public void onException(Throwable throwable) {
                        System.out.println(throwable);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("异步发送完毕，等待回调");
        // end-for
        // sleep一会儿
        // 由于采用的是异步发送，所以若这里不sleep，
        // 则消息还未发送就会将producer给关闭，报错
        Thread.sleep(10000);
        producer.shutdown();
    }

}
